package oa.base.util;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 文件写
 * @author lilang
 *
 */
public class FileWrite {

	
	
	/**
	 * 字符流 写入操作  msg code
	 * 
	 * @param file
	 *            文件路径
	 * @param msg
	 *            需要写入的内容
	 * @param code
	 *            写入编码
	 */
	public static void writeString(String file, String msg, String code) {
		File temp = new File(file);
		try {
			DataOutputStream uts = new DataOutputStream(new FileOutputStream(temp));
			uts.write(msg.getBytes(code));
			uts.flush();
			uts.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	
	/**
	 * 一行一行的写入数据
	 * 
	 * @param path
	 *            写入文件路径
	 * @param o
	 *            写入数据的数组(字符串必须)
	 */
	private static void writeLineByObject(File file, Object[] o) {
		try {
			FileWriter fw = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(fw);
			for (int i = 0; i < o.length; i++) {
				bw.write(String.valueOf(o[i]));
				if (i != o.length - 1) {
					bw.newLine();
				}
			}
			bw.flush();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 一行一行的写入数据
	 * 
	 * @param path
	 *            写入文件路径
	 * @param o
	 *            写入数据的数组
	 */
	public static void writeLine(File file, List<String> o) {
		writeLineByObject(file, o.toArray());
	}
	
	/**
	 * 一行一行的写入数据
	 * 
	 * @param path
	 *            写入文件路径
	 * @param o
	 *            写入数据的数组
	 */
	public static void writeLine(File file, String[] o) {
		writeLineByObject(file, o);
	}
	
	/**
	 * 写入 buffer code 
	 * 
	 * @param path
	 *            写入文件路径
	 * @param o
	 *            写入数据
	 * @param encode
	 *            编码
	 * @author lilang
	 */
	public static void writeLogs(String path, String o, String encode) {
		File file = new File(path);
		try {
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encode));
			bw.write(o);
			bw.flush();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
